import Message from 'Component/Message'

/**
 *
 * 函数调用Message弹出
 * 使用api.open(message) 来弹出Message
 * message: 标题 (字符串或者element node)
 *
 */

let messageInstance

function getMessageInstance(props) {
  if (messageInstance) {
    return messageInstance
  }

  messageInstance = Message.newInstance({
    ...props,
  })

  return messageInstance
}

function removeMessage() {
  if (messageInstance) {
    messageInstance.destroy()
    messageInstance = null
  }
}

function openMessage(message, duration) {
  const instance = getMessageInstance({ message })
  instance.open()

  setTimeout(() => {
    removeMessage()
  }, duration)
}

const api = {
  open(message, duration = 3000) {
    openMessage(message, duration)
  },
}

export default api
